package cn.lccabc.array.no0454;

import java.util.*;

/**
 * @program: leet-code
 * @description: 四数相加 II
 * 给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ，使得 A[i] + B[j] + C[k] + D[l] = 0。
 *
 * 为了使问题简单化，所有的 A, B, C, D 具有相同的长度 N，且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间，最终结果不会超过 231 - 1 。
 *
 * 例如:
 *
 * 输入:
 * A = [ 1, 2]
 * B = [-2,-1]
 * C = [-1, 2]
 * D = [ 0, 2]
 *
 * 输出:
 * 2
 *
 * 解释:
 * 两个元组如下:
 * 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
 * 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
 * @author: LiCC
 * @create: 2019-12-30 23:04
 */
public class Solution {

    public static int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        int count = 0;
        if (A.length == 0 || B.length == 0 || C.length == 0 || D.length == 0) return count;
        Arrays.sort(A);
        Arrays.sort(B);
        Map<Integer, Integer> cd = new HashMap<>();
        int min = C[0] + D[0], max = C[0] + D[0];
        for (int c : C){
            for (int d : D){
                int sum = c + d;
                if (min > sum) min = sum;
                if (max < sum) max = sum;
                if (cd.containsKey(sum)){
                    cd.put(sum, cd.get(sum) + 1);
                } else {
                    cd.put(sum, 1);
                }
            }
        }
        for (int a : A) {
            if ((a + B[0] + min) > 0) break;
            if ((a + B[B.length - 1] + max) < 0) continue;
            for (int b : B) {
                if ((a + b + min) > 0) continue;
                if ((a + b + max) < 0) continue;
                int target = 0 - a - b;
                if (cd.containsKey(target)){
                    count += cd.get(target);
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int A[] = new int[]{-1, -1}, B[] = new int[]{-1, 1}, C[] = new int[]{-1, 1}, D[] = new int[]{1, -1};
        int result = fourSumCount(A, B, C, D);
        System.out.println(result);
    }
}
